package kyuuri.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RssNicoLiveData extends HttpServlet {
	private final String RSS_URL = "http://live.nicovideo.jp/recent/rss?sort=start&";
	private final int BUFFER_SIZE = 128 * 1024;
	private final int P_LIMIT = 100;
	private final static long serialVersionUID = 0;
	private String header = 
		"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
		"<rss version=\"2.0\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:nicolive=\"http://live.nicovideo.jp/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">" +
		"<channel>\n";
	private String footer = 
		"</channel></rss>";

	private String getBody(String rss) {
		rss = rss.replace("<nicolive:", "<");
		rss = rss.replace("</nicolive:", "</");
		int start = rss.indexOf("<item>");
		int end = rss.lastIndexOf("</channel>") - 1;
		return rss.substring(start, end);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
			throws ServletException, IOException {

		resp.setContentType("application/xml");
		resp.setCharacterEncoding("UTF-8");
		
		String body = "";
		for (int i = 0; i < P_LIMIT; i++) {
			URL url = new URL(RSS_URL + "p=" + i);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(url.openStream(), "UTF-8"));
	
			char buf[] = new char[BUFFER_SIZE];
			reader.read(buf, 0, BUFFER_SIZE);
			String rss = String.valueOf(buf);
			if (!rss.contains("<item>"))
				break;
			body = body + getBody(String.valueOf(buf));
		}
		
		PrintWriter out = resp.getWriter();
		out.print(header + body + footer);
		out.flush();
	}
}